package me.pinion.model;

import com.jfinal.plugin.activerecord.TableInfoMapping;
import me.pinion.Log;
import me.pinion.model.annotation.TableBind;

import java.util.List;

@TableBind(table = "x_subscription")
public class Subscription extends XModel<Subscription> {

    public static Subscription dao = new Subscription();

    public Subscription subscribe(XModel model, User user) {
        Subscription subscription = Subscription.dao.findFirst(
                "SELECT * FROM x_subscription WHERE user=? AND target_id=? AND target_type=?"
                , user.getId()
                , model.getId()
                , ModelType.dao.getByClass(model.getClass()).getId());

        if (subscription == null) {
            subscription = new Subscription();
            try {
                subscription.set("user", user.getId());
            } catch (NullPointerException e) {
                Log.e(e);
                throw new RuntimeException();
            }
            subscription.set("target_id", model.getId());
            subscription.set("target_type", model.getModeType().getId());
            subscription.save();
        }
        return subscription;
    }

    public Subscription subscribe(Class<? extends XModel<?>> clazz, Object id, User user) {
        return this.subscribe(ModelType.dao.getModel(clazz, id), user);
    }

    public Subscription subscribe(String className, Object id, User user) {
        return this.subscribe(ModelType.dao.getModel(className, id), user);
    }


    public <T extends XModel<T>> List<T> byUserAndClass(User user, Class<T> clazz, int offset, int max) {
        T dao = ModelType.dao.getByClass(clazz).getModelDAO();
        String tablename = TableInfoMapping.me().getTableInfo(clazz).getTableName();
        return dao.paginate(offset, max, "SELECT t.*", " FROM " + tablename + " AS t WHERE t.id IN (SELECT subs.target_id FROM x_subscription AS subs WHERE subs.target_type=? AND subs.user=?)"
                , ModelType.dao.getByClass(clazz).getId()
                , user.getId()).getList();
    }

}
